package au.id.weston.scott.Vincent;

// Copyright (c) 2009, Scott Weston <scott@weston.id.au>
// All rights reserved.
// 
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// 
//     * Redistributions of source code must retain the above copyright notice,
//       this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright notice,
//       this list of conditions and the following disclaimer in the documentation
//       and/or other materials provided with the distribution.
//     * Neither the name of Scott Weston nor the names of contributors may be
//       used to endorse or promote products derived from this software without
//       specific prior written permission.
// 
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.util.Log;

public class sambaBroadcastReceiver extends BroadcastReceiver {
	
	private final static String TAG = "sambaBroadcastReceiver";

	@Override
	public void onReceive(Context context, Intent intent) {
		String bssid;
		
		Log.d(TAG, "received: " + intent.toString());
		
		if (intent.getAction().equals(android.content.Intent.ACTION_BOOT_COMPLETED)) {
			context.startService(new Intent(context, sambaservice.class));
		} else if (intent.getAction().equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
			Log.d(TAG, "WIFI_STATE_CHANGED_ACTION arrived extras: " + intent.getExtras().keySet());
		} else if (intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
			Log.d(TAG, "NETWORK_STATE_CHANGED_ACTION arrived extras: " + intent.getExtras().keySet());
			Log.d(TAG, "bssid=" + intent.getStringExtra(WifiManager.EXTRA_BSSID));
			NetworkInfo nwi = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);

			// onBootComplete start our service?
			// onWifiChange kick off copies that match our BSSID?

			if (nwi.isAvailable()) {
				DatabaseHelper dbh = new DatabaseHelper(context);
				SQLiteDatabase db = dbh.getReadableDatabase();
				SQLiteQueryBuilder mqb = new SQLiteQueryBuilder();
				mqb.setTables(DatabaseHelper.BSSID_TABLE);

				bssid = intent.getStringExtra(WifiManager.EXTRA_BSSID);
				if (bssid != null && nwi.isConnectedOrConnecting()) {			
					String[] projection = { "mount_id" };
					String[] sargs = { bssid };
					Cursor c = mqb.query(db, projection, "bssid=?", sargs, null, null, null);
					if (c.getCount() != 0) {
						Log.d(TAG, "matching mounts: "  + c.getCount());
						c.moveToFirst();
						while (!c.isAfterLast()) {
							Log.d(TAG, "id=" + c.getInt(c.getColumnIndex("mount_id")));
							Intent copy = new Intent(sambaservice.ACTION_COPY);
							Cursor mountCursor = dbh.getMountById(c.getInt(c.getColumnIndex("mount_id")));
							mountCursor.moveToFirst();
							copy.putExtra("username", mountCursor.getString(mountCursor.getColumnIndex("username")));
							copy.putExtra("password", mountCursor.getString(mountCursor.getColumnIndex("password")));
							copy.putExtra("server", mountCursor.getString(mountCursor.getColumnIndex("server")));
							copy.putExtra("share", mountCursor.getString(mountCursor.getColumnIndex("share")));
							copy.putExtra("directory", mountCursor.getString(mountCursor.getColumnIndex("directory")));
							copy.putExtra("dest", mountCursor.getString(mountCursor.getColumnIndex("destination")));
							copy.putExtra("mount_name", mountCursor.getString(mountCursor.getColumnIndex("mount_name")));
							copy.putExtra("delay", 5000L);
							context.sendBroadcast(copy);
							Log.d(TAG, "Sent DELAYED copy request to service");
							mountCursor.close();
							c.moveToNext();
						}
					} else {
						Log.d(TAG, "no mounts for bssid: "  + bssid);
					}
					c.close();
				} else {
					Log.d(TAG, "no supplied bssid.");
				}
				db.close();
			}
		}
	}
}
